﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Lacrima.Framework.Persistence
{
    public class MySQLEntityMapper : IEntityMapper
    {
        public string EntityToTable<TEntity>(TEntity entity)
        {
            StringBuilder tableStructure = new StringBuilder();
            Type entityType = typeof(TEntity);

            tableStructure.Append(" CREATE TABLE ");
            tableStructure.Append(string.Format(" `{0}` (", entityType.Name));
            PropertyInfo[] properties = entityType.GetProperties();

            //string columns = string.Join(",", properties.Select(o =>string.Format(" `{0}` {1}", o.Name, MySQLMapper.GetMapType(o.PropertyType.Name))));
            foreach (var property in properties)
            {
                string columnType = MySQLMapper.GetMapType(property.PropertyType.Name);
                string columnName = property.Name;
                if (!string.IsNullOrEmpty(columnType))
                {
                    tableStructure.Append(string.Format(" `{0}` {1},", columnName, columnType));
                }
            }
            string table = tableStructure.ToString().TrimEnd(',');
            string ret = string.Format("{0} ) ENGINE=InnoDB DEFAULT CHARSET=utf8;", table);
            //tableStructure.Append(" ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ");
            return ret;
        }
    }
}
